package org.example.tliaswebmanagement.aop;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.example.tliaswebmanagement.mapper.OperateLogMapper;
import org.example.tliaswebmanagement.pojo.OperateLog;
import org.example.tliaswebmanagement.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

// 切面类
@Slf4j
@Aspect
@Component
public class LogAspect {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OperateLogMapper operateLogMapper;

    @Around("@annotation(org.example.tliaswebmanagement.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {

        // 操作人ID - 当前登录员工ID
        // 获取请求头中的jwt令牌，解析令牌
        String jwt = request.getHeader("token");
        Claims claims = JwtUtils.parseJwt(jwt);
        Integer operateUser = (Integer) claims.get("id");

        // 获取操作时间
        LocalDateTime operateTime = LocalDateTime.now();

        // 1、 获取 目标方法的类名
        String className = joinPoint.getTarget().getClass().getName();
        log.info("目标对象的类名：{}", className);

        // 2、 获取 目标方法的方法名
        String methodName = joinPoint.getSignature().getName();
        log.info("目标方法的方法名：{}", methodName);

        // 3、 获取 目标方法运行时传入的参数
        Object[] args = joinPoint.getArgs();
        String methodParams = Arrays.toString(args);
        log.info("目标方法运行时传入的参数：{}", methodParams);

        // 记录开始时间
        long start = System.currentTimeMillis();

        // 4、 目标方法执行的放行
        Object result = joinPoint.proceed();
        // 获取方法返回值
        String returnValue = JSON.toJSONString(result);

        // 5、 获取 目标方法的运行的返回值
        log.info("目标方法的返回值：{}", returnValue);

        // 获取方法执行的耗时
        // 记录结束时间
        long end = System.currentTimeMillis();
        long costTime = end - start;
        log.info(methodName + "方法执行耗时：{}ms",  costTime);

        // 记录操作日志
        OperateLog operateLog = new OperateLog(null, operateUser, operateTime, className, methodName, methodParams,
                returnValue, costTime);
        operateLogMapper.insert(operateLog);

        log.info("Aop记录操作日志：{}", operateLog);

        return result;

    }

}
